package com.ghy.springredis.redisson;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author: 卢佳新
 * @version: v1.0
 * @description: com.ghy.springredis.redisson
 * @date:2022/6/11 15:34
 * @Motto 不积跬步，无以至千里；不积小流，无以成江海。
 */
@RestController
@RequestMapping("/redisson")
public class RedissonController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @GetMapping("/save")
    public String save(){
        stringRedisTemplate.opsForValue().set("key","redisson");
        return "save ok";
    }

    @GetMapping("/get")
    public String get() throws InterruptedException {

        RLock lock=redissonClient.getLock ( "myLock" );
        String str=null;
            if (lock.tryLock (1000,10,TimeUnit.SECONDS)){
                System.out.println ("拿到了锁");
                str=stringRedisTemplate.opsForValue().get("key");

            }else{
                System.out.println ("没有拿到锁");
            }
            lock.unlock ();

        return str;
    }

}
